package push_client

import (
	"errors"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/levigross/grequests"

	"gitee.com/goframe/lt-collector/common"
	"gitee.com/goframe/lt-collector/libs/abio"
	"gitee.com/goframe/lt-collector/libs/libgin"
	"gitee.com/goframe/lt-collector/libs/pool"
	"gitee.com/goframe/lt-collector/libs/utils"
)

func RegPull() error {
	time.Sleep(time.Second * 2)
	rq := utils.NewRequester()
	rq.SetUrl(fmt.Sprintf("http://%s/pull", common.DefConf.Pull.PullDomain))
	rq.Option().JSON = &common.DefConf.Pull
	rq.SetRequestFunc(func(rp *grequests.Response) (e error) {
		bindBean := new(libgin.ReturnJSON)
		if e = rp.JSON(bindBean); e != nil {
			return
		}
		message := bindBean.Message
		if !rp.Ok {
			return errors.New(message.(string))
		}
		return
	})
	return rq.Request(utils.POST)
}

func PullHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		link := c.Query("link")
		go pool.DefRec.Run(NewPull(link).Download)
		libgin.Return.GinOK(c, "OK")
	}
}

type (
	Pull struct {
		link string
	}
)

func NewPull(link string) *Pull {
	return &Pull{link: link}
}

func (p *Pull) Download() (err error) {
	out := abio.NewAbFile(filepath.Join(abio.SelfDir(), "pull.log"), nil)
	lg := log.New(out, "", log.LstdFlags)
	lg.Printf("开始下载文件:%s\n |", p.link)
	shellString := `cd {root}
rm -rf {pack}
curl -# -o {pack} {link} && (
unzip -qo {pack} -d ./ && {soft} migrate && {soft} restart
)`
	replaceSlice := map[string]string{
		"{root}": abio.SelfDir(),
		"{pack}": packName,
		"{link}": p.link,
		"{soft}": os.Args[0],
	}
	for key, r := range replaceSlice {
		shellString = strings.Replace(shellString, key, r, -1)
	}
	cmdPointer := exec.Command("/bin/bash", "-c", shellString)
	cmdPointer.Stdout = out
	cmdPointer.Stderr = cmdPointer.Stdout
	err = cmdPointer.Run()
	return
}
